package cn.com.headfree.log.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.RowSet;

import org.springframework.stereotype.Repository;

import com.gta.edu.sdk.base.dao.impl.BaseDaoImpl;
import com.gta.edu.sdk.common.dto.ChartDto;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.common.dto.Sort;
import com.gta.edu.sdk.log.entity.TLogWarn;
import com.gta.edu.sdk.log.entity.TSysLogInfo;
import com.gta.edu.sdk.util.IdGen;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.log.dao.ILogDao;
import cn.com.headfree.log.dto.ChartLogDto;
@Repository("logDao")
public class LogDaoImpl extends BaseDaoImpl<TSysLogInfo> implements ILogDao {
	private static final int RECORD_COUNT = 1000;
	
	@Override
	public void saveLogRecord(List<?> logRecords) {
		String temp = "insert into t_sys_log_info(id,log_content,oper,oper_name,op_time,exe_time,op_entity,sys_code,ip,result,del_sign,op_type,log_type) values";
		StringBuilder sql = null;
		Map<String, Object> params = new HashMap<String, Object>(logRecords.size());
		// 循环提交记录次数
		int forNum = logRecords.size() % RECORD_COUNT > 0 ? logRecords.size() / RECORD_COUNT + 1 : logRecords.size() / RECORD_COUNT;
		// 得到循环次数，每次提交100条记录
		int start = 0;
		int end = 0;
		TSysLogInfo info = null;
		Object obj = null;
		for (int i = 0; i < forNum; i++) {
			sql = new StringBuilder(temp);
			start = i * RECORD_COUNT;
			end = (i + 1) * RECORD_COUNT - 1;
			if (i == forNum - 1) {
				end = logRecords.size() - 1;
			}
			for (int j = start; j <= end; j++) {
				obj = logRecords.get(j);
				if (obj != null) {
					info = (TSysLogInfo)obj;
					sql.append("(#{id").append(j).append("},#{logContent").append(j).append("},#{oper").append(j)
							.append("},#{operName").append(j).append("},#{opTime").append(j).append("},#{exeTime").append(j).append("},#{opEntity").append(j)
							.append("},#{sysCode").append(j).append("},#{ip").append(j).append("},#{result").append(j).append("},#{delSign").append(j).append("},#{opType").append(j).append("},#{logType").append(j).append("})");
					if (j != end) {
						sql.append(",");
					}
					
					params.put("id" + j, IdGen.uuid());
					params.put("logContent" + j, info.getLogContent());
					params.put("oper" + j, info.getOper());
					params.put("operName" + j, info.getOperName());
					params.put("opTime" + j, info.getOpTime());
					params.put("exeTime" + j, info.getExeTime());
					params.put("opEntity" + j, info.getOpEntity());
					params.put("sysCode" + j, info.getSysCode());
					params.put("ip" + j, info.getIp());
					params.put("result" + j, info.getResult());
					params.put("delSign" + j, 0);
					params.put("opType" + j, info.getOpType());
					params.put("logType" + j, info.getLogType());
				}
			}
			this.executeSql(sql.toString(), params);
		}
	}

	@Override
	public void findPageLog(TSysLogInfo logInfo,Date startTime,Date endTime,Sort sort, Page<TSysLogInfo> page) {
		List<Object> params = new ArrayList<Object>();
		if (!StringUtil.isNullOrEmpty(sort.getFields())) {
			if (sort.getFields().contains("resultValue")) {
				sort.setFields(sort.getFields().replace("resultValue", "result"));
			}
		}
        StringBuffer sql = new StringBuffer("select * from t_sys_log_info where (del_sign=0 or del_sign=2) ");
        if (logInfo != null) {
        	if (!StringUtil.isNullOrEmpty(logInfo.getSysCode())) {
        		sql.append(" and sys_code=? ");
        		params.add(logInfo.getSysCode());
        	}
        	if (!StringUtil.isNullOrEmpty(logInfo.getIp())) {
        		sql.append(" and ip like ? ");
        		params.add("%" + logInfo.getIp() + "%");
        	}
        	if (!StringUtil.isNullOrEmpty(logInfo.getLogType())) {
        		sql.append(" and log_type = ? ");
        		params.add(logInfo.getLogType());
        	}
        	if (!StringUtil.isNullOrEmpty(logInfo.getLogContent())) {
        		sql.append(" and log_content like ? ");
        		params.add("%" + logInfo.getLogContent() + "%");
        	}
        	if (logInfo.getResult() != null && !logInfo.getResult().equals(-1)) {
        		sql.append(" and result=? ");
        		params.add(logInfo.getResult());
        	}
        	if (!StringUtil.isNullOrEmpty(logInfo.getOpType()) && !"-1".equals(logInfo.getOpType())) {
        		sql.append(" and op_type=? ");
        		params.add(logInfo.getOpType());
        	}
        	if (!StringUtil.isNullOrEmpty(logInfo.getOper())) {
        		sql.append(" and (oper like ? or oper_name like ?) ");
        		params.add("%" + logInfo.getOper() + "%");
        		params.add("%" + logInfo.getOper() + "%");
        	}
        	if (startTime != null) {
        		sql.append(" and op_time>? ");
        		params.add(startTime);
        	}
        	if (endTime != null) {
        		sql.append(" and op_time<? ");
        		params.add(endTime);
        	}
        }
        this.findAsPageBySql(TSysLogInfo.class, sql.toString(), page, sort, false, params.toArray());
	}

	@Override
	public List<ChartDto> logOpSummary(String sysCode, Date startTime, Date endTime) {
		StringBuilder sql = new StringBuilder("select op_type as label,count(*) as value from t_sys_log_info where del_sign=0 ");
		List<Object> params = new ArrayList<Object>(3);
		if (!StringUtil.isNullOrEmpty(sysCode)) {
			sql.append(" and sys_code=? ");
			params.add(sysCode);
		}
		if (startTime != null) {
			sql.append(" and op_time > ? ");
			params.add(startTime);
		}
		
		if (endTime != null) {
			sql.append(" and op_time < ? ");
			params.add(endTime);
		}
		sql.append(" group by op_type ");
		return this.findAllBySQL(ChartDto.class, sql.toString(), null, false, params.toArray());
	}

	@Override
	public List<ChartLogDto> logOpExceptionSummary(String sysCode, Date startTime, Date endTime) {
		StringBuilder sql = new StringBuilder("select result as label,count(*) as value from t_sys_log_info where del_sign=0 ");
		List<Object> params = new ArrayList<Object>(3);
		if (!StringUtil.isNullOrEmpty(sysCode)) {
			sql.append(" and sys_code=? ");
			params.add(sysCode);
		}
		if (startTime != null) {
			sql.append(" and op_time > ? ");
			params.add(startTime);
		}
		
		if (endTime != null) {
			sql.append(" and op_time < ? ");
			params.add(endTime);
		}
		sql.append(" group by result ");
		return this.findAllBySQL(ChartLogDto.class, sql.toString(), null, false, params.toArray());
	}
	
	public int getLogRecordNum() throws SQLException {
		String sql = "select count(1) from t_sys_log_info where del_sign=0";
		RowSet rs = this.queryset(sql);
		if (rs != null && rs.next()) {
			return rs.getInt(1);
		} 
		return 0;
	}
	
	@Override
	public void findPageLogWarn(Sort sort, Page<TLogWarn> page) {
		if (!StringUtil.isNullOrEmpty(sort.getFields())) {
			if (sort.getFields().contains("warnTypeName")) {
				sort.setFields(sort.getFields().replace("warnTypeName", "warnType"));
			}
		}
		StringBuffer sql = new StringBuffer("select * from t_log_warn ");
		this.findAsPageBySql(TLogWarn.class, sql.toString(), page, sort, false);
	}
	
	@Override
	public void logBack(Date limitDate,int flag) {
		Map<String, Object> params = new HashMap<String, Object>(1);
		String sql = "update t_sys_log_info set del_sign=#{flag} where op_time<#{limitDate} and del_sign!=1";
		params.put("flag", flag);
		params.put("limitDate", limitDate);
		this.executeSql(sql, params);
	}
	
	@Override
	public void clearRecord() {
		String sql = "delete from t_log_warn ";
		this.executeSql(sql, new HashMap<String, Object>());
	}
}
